package com.cspg.design.ui.schemeActivity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.cspg.design.CSPGApplication;
import com.cspg.design.R;
import com.cspg.design.adapter.Style;
import com.cspg.design.bean.UserInfo;
import com.cspg.design.bean.modelLibrary.TowerLibrary;
import com.cspg.design.bean.modelLibrary.TransformerLibrary;
import com.cspg.design.bean.modelLibrary.WireLibrary;
import com.cspg.design.bean.shemeBean.MyHighVoltageSchemeBean;
import com.cspg.design.bean.shemeBean.MyLowVoltageSchemeBean;
import com.cspg.design.dao.gen.DaoSession;
import com.cspg.design.dao.gen.MyHighVoltageSchemeBeanDao;
import com.cspg.design.dao.gen.MyLowVoltageSchemeBeanDao;
import com.cspg.design.dao.gen.TowerLibraryDao;
import com.cspg.design.dao.gen.WireLibraryDao;
import com.cspg.design.presenter.SchemePresenter;
import com.cspg.design.utils.ActionBarUtil;
import com.cspg.design.utils.StatusBarUtil;
import com.cspg.design.utils.Utils;
import com.cspg.design.widget.AlertListDialog;
import com.cspg.design.widget.Loading;
import com.cspg.design.widget.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

public class MyLowVoltageSchemeEditActivity extends AppCompatActivity {

    private final List<String> wireModelList = new ArrayList<>();
    private final List<String> poleModelList = new ArrayList<>();
    private final List<WireLibrary> wireBeanList = new ArrayList<>();
    private final List<TowerLibrary> poleBeanList = new ArrayList<>();
    private WireLibrary selectWire380;
    private WireLibrary selectWire220;
    private final List<TransformerLibrary> transformerModelList = new ArrayList<>();
    private DaoSession daoSession;
    private List<TowerLibrary> choicePoles = new ArrayList<>();
    private EditText et_transformer_model;
    private EditText et_wire_model_380;
    private EditText et_wire_model_220;
    private EditText et_flat_ground;
    private EditText et_hilly_area; /*山地*/
//    private EditText et_high_mountain; //高山</string>
    private EditText et_hills; //丘陵</string>
    private EditText et_common_soil; //普通土</string>
    private EditText et_hard_soil; //坚土</string>
    private EditText et_loose_sandstone; //松砂石</string>
    private EditText et_mud_puddle; //泥水坑</string>
    private EditText et_rock; //岩石</string>
    private MyLowVoltageSchemeBean myLowVoltageSchemeBean;


    private ListView poleDialogListView = null;
    private SchemePresenter schemePresenter;
    private EditText etTransformer;
    private Button btn_design_model= null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_low_voltage_scheme_edit);
        StatusBarUtil.setStatusBarColor(this, R.color.colorPrimary);
        Intent intent = getIntent();
        String code = intent.getStringExtra("code");
        myLowVoltageSchemeBean = (MyLowVoltageSchemeBean) intent.getSerializableExtra("bean");
        if (code == null || myLowVoltageSchemeBean == null)
        {
            ToastUtils.toast(this,"传入参数错误。。。");
            return;
        }
        daoSession = ((CSPGApplication)getApplication()).getDaoSession();
        myLowVoltageSchemeBean = daoSession.getMyLowVoltageSchemeBeanDao().queryBuilder()
                .where(MyLowVoltageSchemeBeanDao.Properties.SchemeUUID.eq(myLowVoltageSchemeBean.getSchemeUUID()))
                .unique();
        if (code.equals("0")) //修改
        {
            ActionBarUtil.setActionBar(this, R.string.my_edit_scheme);
        } else  //浏览
        {
            ActionBarUtil.setActionBar(this, R.string.my_look_scheme);
        }
        if (myLowVoltageSchemeBean == null)
        {
            ToastUtils.toast(this,"传入参数错误。。。");
            return;
        }
        Utils.closeBoard(this);//隐藏键盘
        schemePresenter = new SchemePresenter(this,null,null);
        daoSession = ((CSPGApplication) getApplication()).getDaoSession();

        etTransformer = findViewById(R.id.sp_my_low_voltage_scheme_transformer);


        btn_design_model = findViewById(R.id.btn_my_low_voltage_scheme_design_model_edit);
        btn_design_model.setOnClickListener(v -> {
            showPoleAlertDialog();
        });
        Button btn_design_model_look = findViewById(R.id.btn_my_low_voltage_scheme_design_model_look);
        btn_design_model_look.setOnClickListener(v -> {
            lookPoleAlertDialog();
        });

        Button btn_save = findViewById(R.id.btn_my_low_voltage_scheme_save);

        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.closeBoard(MyLowVoltageSchemeEditActivity.this);//隐藏键盘
                new Thread() {
                    @Override
                    public void run() {
                        saveData();
                    }
                }.start();
            }
        });
        et_transformer_model = findViewById(R.id.sp_my_low_voltage_scheme_transformer);
        et_wire_model_380 = findViewById(R.id.sp_my_low_voltage_scheme_wire_model_380);
        et_wire_model_220 = findViewById(R.id.sp_my_low_voltage_scheme_wire_model_220);
        et_flat_ground = findViewById(R.id.et_my_low_voltage_flat_ground);
        et_hilly_area = findViewById(R.id.et_my_low_voltage_hilly_area); /*山地*/
//        et_high_mountain = findViewById(R.id.et_my_low_voltage_high_mountain); //高山</string>
        et_hills = findViewById(R.id.et_my_low_voltage_hills); //丘陵</string>
        et_common_soil = findViewById(R.id.et_my_low_voltage_common_soil); //普通土</string>
        et_hard_soil = findViewById(R.id.et_my_low_voltage_hard_soil); //坚土</string>
        et_loose_sandstone = findViewById(R.id.et_my_low_voltage_loose_sandstone); //松砂石</string>
        et_mud_puddle = findViewById(R.id.et_my_low_voltage_mud_puddle); //泥水坑</string>
        et_rock = findViewById(R.id.et_my_low_voltage_rock); //岩石</string>
        choicePoles = getPole(myLowVoltageSchemeBean.getTypicalDesignModel());
        if (!code.equals("0")) //修改
        {
            btn_design_model.setClickable(false);
            btn_save.setVisibility(View.INVISIBLE);
            btn_design_model.setVisibility(View.INVISIBLE);


            et_transformer_model.setClickable(false);
            et_transformer_model.setFocusable(false);
            et_transformer_model.setSelected(false);

            et_wire_model_220.setClickable(false);
            et_wire_model_220.setFocusable(false);

            et_wire_model_380.setClickable(false);
            et_wire_model_380.setFocusable(false);

            et_flat_ground.setClickable(false);
            et_flat_ground.setFocusable(false);

            et_hilly_area.setClickable(false);
            et_hilly_area.setFocusable(false);

//            et_high_mountain.setClickable(false);
//            et_high_mountain.setFocusable(false);

            et_hills.setClickable(false);
            et_hills.setFocusable(false);

            et_common_soil.setClickable(false);
            et_common_soil.setFocusable(false);

            et_hard_soil.setClickable(false);
            et_hard_soil.setFocusable(false);

            et_loose_sandstone.setClickable(false);
            et_loose_sandstone.setFocusable(false);

            et_mud_puddle.setClickable(false);
            et_mud_puddle.setFocusable(false);

            et_rock.setClickable(false);
            et_rock.setFocusable(false);
        }
        else
        {
            etTransformer.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showTransformAlertDialog();
                }
            });
            EditText etWire380 = findViewById(R.id.sp_my_low_voltage_scheme_wire_model_380);
            etWire380.setOnClickListener(v -> new AlertListDialog.ListBuilder(MyLowVoltageSchemeEditActivity.this)
                    .setDividerColorRes(R.color.color_divider)
                    .setDividerHeightRes(R.dimen.dp1)
                    .setTitle("选择导线型号")
                    .setIcon(R.drawable.ic_info)
                    .setItems(wireModelList.toArray(new String[wireModelList.size()]), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            etWire380.setText(wireModelList.get(which));
                            selectWire380 = wireBeanList.get(which);
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).create().show());
            EditText etWire220 = findViewById(R.id.sp_my_low_voltage_scheme_wire_model_220);
            etWire220.setOnClickListener(v -> new AlertListDialog.ListBuilder(MyLowVoltageSchemeEditActivity.this)
                    .setDividerColorRes(R.color.color_divider)
                    .setDividerHeightRes(R.dimen.dp1)
                    .setTitle("选择导线型号")
                    .setIcon(R.drawable.ic_info)
                    .setItems(wireModelList.toArray(new String[wireModelList.size()]), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            etWire220.setText(wireModelList.get(which));
                            selectWire220 = wireBeanList.get(which);
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).create().show());
        }

        initData();
    }

    private void initData() {

        daoSession.getWireLibraryDao().queryBuilder().rx().list().observeOn(AndroidSchedulers.mainThread()).subscribe(
                wireLibraries -> {
                    for (int i = 0; i < wireLibraries.size(); i++) {
                        wireModelList.add(wireLibraries.get(i).getWireModel());
                        wireBeanList.add(wireLibraries.get(i));
                    }
                }
        );

        daoSession.getTowerLibraryDao().queryBuilder().rx().list().observeOn(AndroidSchedulers.mainThread()).subscribe(
                towerLibraries -> {
                    for (int i = 0; i < towerLibraries.size(); i++) {
                        poleModelList.add(towerLibraries.get(i).getPoleModel());
                        poleBeanList.add(towerLibraries.get(i));
                    }
                }
        );
        daoSession.getTransformerLibraryDao().queryBuilder().rx().list().observeOn(AndroidSchedulers.mainThread()).subscribe(
                transformerLibraries -> {
                    transformerModelList.addAll(transformerLibraries);
                }
        );


        if (myLowVoltageSchemeBean != null) {
            et_transformer_model.setText(myLowVoltageSchemeBean.getTransformerModel());
            et_wire_model_380.setText(myLowVoltageSchemeBean.getWireModel380V());
            et_wire_model_220.setText(myLowVoltageSchemeBean.getWireModel220V());
            et_flat_ground.setText(myLowVoltageSchemeBean.getFlatGround());
            et_hilly_area.setText(myLowVoltageSchemeBean.getHillyArea()); /*山地*/
//            et_high_mountain.setText(myLowVoltageSchemeBean.getHighMountain()); //高山</string>
            et_hills.setText(myLowVoltageSchemeBean.getHills()); //丘陵</string>
            et_common_soil.setText(myLowVoltageSchemeBean.getCommonSoil()); //普通土</string>
            et_hard_soil.setText(myLowVoltageSchemeBean.getHardSoil()); //坚土</string>
            et_loose_sandstone.setText(myLowVoltageSchemeBean.getLooseSandstone()); //松砂石</string>
            et_mud_puddle.setText(myLowVoltageSchemeBean.getMudPuddle()); //泥水坑</string>
            et_rock.setText(myLowVoltageSchemeBean.getRock()); //岩石</string>s
        }
    }

    private void showPoleAlertDialog() {
        Utils.closeBoard(this);
        List<TowerLibrary> towerLibraryList380 = daoSession.getTowerLibraryDao().queryBuilder()
                .where(TowerLibraryDao.Properties.VoltageLevel.like("%380%"))
                .list();
        List<TowerLibrary> towerLibraryList220 = daoSession.getTowerLibraryDao().queryBuilder()
                .where(TowerLibraryDao.Properties.VoltageLevel.like("%220%"))
                .list();
        List<TowerLibrary> filterTowerLibraryList = new ArrayList<>();
        List<String> towerList = new ArrayList<>();
        String[] towerNames ;
        boolean[] isChoice ;
        if (selectWire380 == null)
        {
            for (int i = 0; i < towerLibraryList380.size(); i++) {
                TowerLibrary towerLibrary = towerLibraryList380.get(i);
                filterTowerLibraryList.add(towerLibrary);
            }
        }
        else
        {
            int cross_section = Integer.parseInt(selectWire380.getWireCrossSection());
            for (int i = 0; i < towerLibraryList380.size(); i++) {
                TowerLibrary towerLibrary = towerLibraryList380.get(i);
                int maxCrossSection = Integer.parseInt(towerLibrary.getMaxWireCrossSection());
                int minCrossSection = Integer.parseInt(towerLibrary.getMiniWireCrossSection());
                if (cross_section >= minCrossSection && cross_section <= maxCrossSection
                        && towerLibrary.getWireQuality().equals(selectWire380.getWireQuality())) {
                    towerList.add(towerLibrary.getPoleModel());
                    filterTowerLibraryList.add(towerLibrary);
                }
            }
        }
        if (selectWire220 == null)
        {
            for (int i =0 ; i< towerLibraryList220.size();i++)
            {
                TowerLibrary towerLibrary = towerLibraryList220.get(i);
                filterTowerLibraryList.add(towerLibrary);
            }

        }
        else {
            int cross_section = Integer.parseInt(selectWire220.getWireCrossSection());
            for (int i = 0; i < towerLibraryList220.size(); i++) {
                TowerLibrary towerLibrary = towerLibraryList220.get(i);
                int maxCrossSection = Integer.parseInt(towerLibrary.getMaxWireCrossSection());
                int minCrossSection = Integer.parseInt(towerLibrary.getMiniWireCrossSection());
                if (cross_section >= minCrossSection && cross_section <= maxCrossSection
                        && towerLibrary.getWireQuality().equals(selectWire220.getWireQuality())) {
                    towerList.add(towerLibrary.getPoleModel());
                    filterTowerLibraryList.add(towerLibrary);
                }
            }
        }
        towerNames = new String[filterTowerLibraryList.size()];
        isChoice = new boolean[filterTowerLibraryList.size()];
        for (int i = 0 ; i< filterTowerLibraryList.size();i++)
        {
            towerNames[i] = filterTowerLibraryList.get(i).getPoleModel();
            isChoice[i] = false;
        }
        choicePoles.clear();
        if (towerNames.length == 0)
        {
            towerNames =  new String[] {"没有数据"};
        }
        String[] finalTowerNames = towerNames;
        android.app.AlertDialog alertDialog = new AlertListDialog.ListBuilder(this).
                setDividerColorRes(R.color.color_divider)
                .setDividerHeightRes(R.dimen.dp1)
                .setTitle("选择杆塔型号")
                .setIcon(R.drawable.ic_info)
                .setMultiChoiceItems(towerNames, isChoice, (dialog, which, isChecked) -> {
                    if (isChecked) {
                        if (!finalTowerNames[which].equals("没有数据")) {
                            choicePoles.add(filterTowerLibraryList.get(which));
                        }
                    }
                }).setNeutralButton("全选",null).setCancelable(true).setPositiveButton("确定",(dialog, v)->{
                    Button btn_design_model = findViewById(R.id.btn_my_low_voltage_scheme_design_model_edit);
                    if(choicePoles.size() != 0)
                    {
                        btn_design_model.setText("修改");
                    }
                    dialog.dismiss();
                }).setNegativeButton("取消",(dialog,which)->{
                    choicePoles.clear();
                    dialog.dismiss();
                }).create();
        poleDialogListView = alertDialog.getListView();
        alertDialog.show();
        Button btn = alertDialog.getButton(android.app.AlertDialog.BUTTON_NEUTRAL);
        if (btn != null)
        {
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (int i = 0; i< filterTowerLibraryList.size();i++)
                    {
                        poleDialogListView.setItemChecked(i,true);
                        choicePoles.add(filterTowerLibraryList.get(i));
                        isChoice[i] = true;
                    }
                }
            });
        }
    }

    private void lookPoleAlertDialog() {
        Utils.closeBoard(this);
        String poleModel = myLowVoltageSchemeBean.getTypicalDesignModel();
        if (poleModel != null) {
            String[] poleModels = poleModel.split("&");
            new AlertListDialog.ListBuilder(this).
                    setDividerColorRes(R.color.color_divider)
                    .setDividerHeightRes(R.dimen.dp1)
                    .setTitle("杆塔型号")
                    .setIcon(R.drawable.ic_info)
                    .setItems(poleModels, (dialog, which) -> {
                    })
                    .setCancelable(true).setPositiveButton("确定", (dialog, v) -> {
                dialog.dismiss();
            }).create().show();
        }
    }

    private void saveData() {

        String tip = "";

        EditText et_transformer_model = findViewById(R.id.sp_my_low_voltage_scheme_transformer);
        EditText et_wire_model_380 = findViewById(R.id.sp_my_low_voltage_scheme_wire_model_380);
        EditText et_wire_model_220 = findViewById(R.id.sp_my_low_voltage_scheme_wire_model_220);
        EditText et_flat_ground = findViewById(R.id.et_my_low_voltage_flat_ground);
        EditText et_hilly_area = findViewById(R.id.et_my_low_voltage_hilly_area); /*山地*/
//        EditText et_high_mountain = findViewById(R.id.et_my_low_voltage_high_mountain); //高山</string>
        EditText et_hills = findViewById(R.id.et_my_low_voltage_hills); //丘陵</string>
        EditText et_common_soil = findViewById(R.id.et_my_low_voltage_common_soil); //普通土</string>
        EditText et_hard_soil = findViewById(R.id.et_my_low_voltage_hard_soil); //坚土</string>
        EditText et_loose_sandstone = findViewById(R.id.et_my_low_voltage_loose_sandstone); //松砂石</string>
        EditText et_mud_puddle = findViewById(R.id.et_my_low_voltage_mud_puddle); //泥水坑</string>
        EditText et_rock = findViewById(R.id.et_my_low_voltage_rock); //岩石</string>
        if (!Utils.isInteger(et_flat_ground.getText().toString())) {
            tip = "平地请输入数字";
        }
//        else if (!Utils.isInteger(et_high_mountain.getText().toString())) {
//            tip = "高山请输入数字";
//        }
        else if (!Utils.isInteger(et_hilly_area.getText().toString())) {
            tip = "山地请输入数字";
        } else if (!Utils.isInteger(
                et_hills.getText().toString())) {
            tip = "丘陵请输入数字";
        }
        if (!tip.isEmpty()) {
            final String msg = tip;
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(() -> {
                Toast.makeText(MyLowVoltageSchemeEditActivity.this, msg, Toast.LENGTH_LONG).show();
                Loading.getIns().target(MyLowVoltageSchemeEditActivity.this).show(Style.CANCEL);
            });
            return;
        }
        int flatGround = Integer.parseInt(et_flat_ground.getText().toString());
        int hillyArea = Integer.parseInt(et_hilly_area.getText().toString());
//        int highMountain = Integer.parseInt(et_high_mountain.getText().toString());
        int hills = Integer.parseInt(et_hills.getText().toString());
        if ((flatGround + hillyArea  + hills) > 100) {
            tip = "各种地形的和不能大于100";
        } else if ((flatGround + hillyArea  + hills) < 100) {
            tip = "各种地形的和不能小于100";
        } else if (!Utils.isInteger(
                et_common_soil.getText().toString())) {
            tip = "普通土请输入数字";
        } else if (!Utils.isInteger(
                et_hard_soil.getText().toString())) {
            tip = "坚土请输入数字";
        } else if (!Utils.isInteger(
                et_loose_sandstone.getText().toString())) {
            tip = "松砂石请输入数字";
        } else if (!Utils.isInteger(et_rock.getText().toString())) {
            tip = "岩石请输入数字";
        } else if (!Utils.isInteger(et_mud_puddle.getText().toString())) {
            tip = "泥水坑请输入数字";
        }
        if (!tip.isEmpty()) {
            final String msg = tip;
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(() -> {
                Toast.makeText(MyLowVoltageSchemeEditActivity.this, msg, Toast.LENGTH_LONG).show();
                Loading.getIns().target(MyLowVoltageSchemeEditActivity.this).show(Style.CANCEL);
            });
            return;
        }
        int loosenSandstone = Integer.parseInt(et_loose_sandstone.getText().toString());
        int commonSoil = Integer.parseInt(et_common_soil.getText().toString());
        int hardSoil = Integer.parseInt(et_hard_soil.getText().toString());
        int mudPuddle = Integer.parseInt(et_mud_puddle.getText().toString());
        int rock = Integer.parseInt(et_rock.getText().toString());
        if ((loosenSandstone + commonSoil + hardSoil + mudPuddle + rock) > 100) {
            tip = "各种地质的和不能大于100";
        } else if ((loosenSandstone + commonSoil + hardSoil + mudPuddle + rock) < 100) {
            tip = "各种地质的和不能小于100";
        } else if (et_transformer_model.getText().toString().trim().equals("")) {
            tip = "请选择变压器型号";
        } else if (et_wire_model_220.getText().toString().trim().equals("")
                && et_wire_model_380.getText().toString().trim().isEmpty()) {
            tip = "至少需要选择一种导线";
        } else if (choicePoles.size() == 0) {
            tip = "请在典型设计模块中添加数据";
        }
        if (!tip.isEmpty()) {
            final String msg = tip;
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(() -> {
                Toast.makeText(MyLowVoltageSchemeEditActivity.this, msg, Toast.LENGTH_LONG).show();
                Loading.getIns().target(MyLowVoltageSchemeEditActivity.this).show(Style.CANCEL);
            });
            return;
        }

        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(() -> {
            String poleModels = "";
            for (int i = 0; i < choicePoles.size(); i++) {
                if ((i + 1) == choicePoles.size()) {
                    poleModels += choicePoles.get(i).getPoleModel();
                } else {
                    poleModels += choicePoles.get(i).getPoleModel() + "&";
                }
            }
            MyLowVoltageSchemeBean myLowVoltageSchemeBeanNew = new MyLowVoltageSchemeBean(
                    null,null,
                    null,
                    et_transformer_model.getText().toString(),
                    et_wire_model_380.getText().toString(),
                    et_wire_model_220.getText().toString(),
                    flatGround + "", hillyArea + "", 0 + "", hills + "",
                    commonSoil + "", hardSoil + "", loosenSandstone + "", mudPuddle + "", rock + "",
                    poleModels, UserInfo.getInstance().userName

            );
            myLowVoltageSchemeBeanNew.setSchemeId(myLowVoltageSchemeBean.getSchemeId());
            myLowVoltageSchemeBeanNew.setSchemeName(myLowVoltageSchemeBean.getSchemeName());
            myLowVoltageSchemeBeanNew.setSchemeUUID(myLowVoltageSchemeBean.getSchemeUUID());
            schemePresenter.updateLowVoltageScheme(myLowVoltageSchemeBeanNew);
        });
    }

    private List<TowerLibrary>  getPole(String poles)
    {
        List<TowerLibrary> towerLibraryList = new ArrayList<>();
        String[]  arrPole = poles.split("&");
        for (int i=0 ;i<arrPole.length;i++)
        {
            String poleModel = arrPole[i];
            towerLibraryList.add(daoSession.getTowerLibraryDao()
                    .queryBuilder()
                    .where(TowerLibraryDao.Properties.PoleModel.eq(poleModel)).unique());
        }
        return towerLibraryList;
    }

    public void showTransformAlertDialog()
    {
        ListView listView = new ListView(this);
        View view = LayoutInflater.from(this).inflate(R.layout.tranformer_dialog_header,null,false);
        listView.addHeaderView(view);
        ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
        for (int i = 0 ; i < transformerModelList.size();i++)
        {
            TransformerLibrary transformerLibrary = transformerModelList.get(i);
            HashMap<String,String> map = new HashMap<>();
            map.put("pole", transformerLibrary.getPoleModel());
            map.put("transformer", transformerLibrary.getTransformerModel());
            map.put("capacity", transformerLibrary.getCapacity());
            dataList.add(map);
        }

        SimpleAdapter adapter = new SimpleAdapter(this, dataList, R.layout.transformer_dialog_item,
                new String[]{"pole", "transformer", "capacity"},
                new int[]{R.id.transformer_dialog_pole, R.id.transformer_dialog_trans, R.id.transformer_dialog_capacity}
        );
        listView.setAdapter(adapter);
        AlertDialog dialog = new  AlertDialog.Builder(this)
                .setView(listView)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).create();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TransformerLibrary transformerLibrary = transformerModelList.get(position - 1);
                etTransformer.setText(transformerLibrary.getPoleModel());
                et_wire_model_380.setText(transformerLibrary.getTo380());
                et_wire_model_220.setText(transformerLibrary.getTo220());
                List<WireLibrary> wireLibrary380s = daoSession.getWireLibraryDao().queryBuilder()
                        .where(WireLibraryDao.Properties.WireModel.eq(transformerLibrary.getTo380())).list();
                if (wireLibrary380s != null && wireLibrary380s.size() > 0)
                {
                    selectWire380 = wireLibrary380s.get(0);
                }
                List<WireLibrary> wireLibrary220s = daoSession.getWireLibraryDao().queryBuilder()
                        .where(WireLibraryDao.Properties.WireModel.eq(transformerLibrary.getTo220())).list();
                if (wireLibrary220s != null && wireLibrary220s.size() > 0)
                {
                    selectWire220 = wireLibrary220s.get(0);
                }
                dialog.dismiss();
            }
        });
        dialog.show();


    }

    /**
     * 点击空白区域隐藏键盘.
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (MyLowVoltageSchemeEditActivity.this.getCurrentFocus() != null) {
                if (MyLowVoltageSchemeEditActivity.this.getCurrentFocus().getWindowToken() != null) {
                    imm.hideSoftInputFromWindow(MyLowVoltageSchemeEditActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
        return super.onTouchEvent(event);
    }
}